package com.mc.moring.login;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.google.gson.Gson;
import com.mc.moring.R;
import com.mc.moring.app.LogUtils;
import com.mc.moring.base.BaseActivity;
import com.mc.moring.base.HttpCallback;
import com.mc.moring.bean.AppConfigBean;
import com.mc.moring.bean.ZiLiPageUserDataBean;
import com.mc.moring.bean.getWebLinkConfigBean;
import com.mc.moring.information.modle.KycModle;
import com.mc.moring.login.modle.LoginModle;
import com.mc.moring.main.WebViewActivity;
import com.mc.moring.main.modle.MianModle;
import com.mc.moring.util.GsonUtils;
import com.mc.moring.util.IntentUtils;
import com.mc.moring.util.MyTextUtils;
import com.mc.moring.util.PointMgr;
import com.mc.moring.util.SharePreUtil;
import com.mc.moring.util.T;
import com.mc.moring.util.ToastUtils;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class ResetPasswordActivity extends BaseActivity {

    TextView back;
    TextView right_text;
    TextView rightText;
    LoginModle loginModle = null;

    EditText et_password;
    ImageView iv_look_up;
    EditText et_password_confirm;
    ImageView iv_look_up_confirm;
    TextView tv_button;
    TextView tv_runtime_error;
    View reset_line2;
    View reset_line1;

    private String password = "";
    private String password_confirm = "";
    private boolean look_up_confirm = false;
    private boolean look_up = false;

    String code = "";

    String mobile = "";

    public KycModle kycModle = null;

    private String isPass = "";

//    private boolean firstCompare = true;

    private getWebLinkConfigBean urlBean;
    private AppConfigBean appConfigBean;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reset_password);
        loginModle = LoginModle.Companion.getInstant();
        kycModle = KycModle.Companion.getInstant();
        Intent intent = getIntent();
        if (intent != null) {
            String code = intent.getStringExtra("smsCode");
            String mobile = intent.getStringExtra("mobile");
            if (code != null) {
                this.code = code;
            }
            if (mobile != null) {
                this.mobile = mobile;
            }
        }
        init();
    }

    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    public void initView() {
        LogUtils.logE("reset pwd");
        back = findViewById(R.id.back);
        rightText = findViewById(R.id.right_text);
        right_text = findViewById(R.id.right_text);
        et_password = findViewById(R.id.et_password);
        iv_look_up = findViewById(R.id.iv_look_up);
        et_password_confirm = findViewById(R.id.et_password_confirm);
        iv_look_up_confirm = findViewById(R.id.iv_look_up_confirm);
        tv_button = findViewById(R.id.tv_button);
        tv_button.setBackgroundResource(R.drawable.bg_f4f4f4_corner_8);
        tv_runtime_error = findViewById(R.id.tv_runtime_error);
        reset_line1 = findViewById(R.id.reset_line1);
        reset_line2 = findViewById(R.id.reset_line2);


        MyTextUtils.INSTANCE.setLengthLimit(et_password, 4, 20);
        MyTextUtils.INSTANCE.setLengthLimit(et_password_confirm, 4, 20);

        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        rightText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showHelp();

            }
        });
        tv_button.setOnClickListener(new View.OnClickListener() {//判断逻辑改为这里处理,要注意显示是否正确，以及修改时提示是否去掉
            @Override
            public void onClick(View v) {
                switch ( isPass ){
                    case "SUCCESS":
                        PointMgr.INSTANCE.sendEvent("cl_login_click_tab_19");
                        Log.e("PointMgr.INSTANCE.sendEvent","cl_login_click_tab_19");

                        tv_runtime_error.setVisibility(View.GONE);

                        reset_line1.setBackgroundColor(Color.parseColor("#33000000"));
                        reset_line2.setBackgroundColor(Color.parseColor("#33000000"));
                        resetPwd(code, password, password_confirm);
                        break;
                    case "NO_ENOUGH_LENGTH":
                        tv_runtime_error.setVisibility(View.VISIBLE);
                        tv_runtime_error.setText("Menos de 4 dígitos");
                        reset_line1.setBackgroundColor(Color.parseColor("#4DFF3737"));
                        reset_line2.setBackgroundColor(Color.parseColor("#4DFF3737"));
                        break;
                    case "ERROR_PASSWORD":
                        tv_runtime_error.setVisibility(View.VISIBLE);
                        tv_runtime_error.setText("Formato erróneo");
                        reset_line1.setBackgroundColor(Color.parseColor("#4DFF3737"));
                        reset_line2.setBackgroundColor(Color.parseColor("#4DFF3737"));
                    case "NO_SAME":
                        tv_runtime_error.setVisibility(View.VISIBLE);
                        tv_runtime_error.setText("La contraseña de entrada es diferente.");
                        reset_line1.setBackgroundColor(Color.parseColor("#4DFF3737"));
                        reset_line2.setBackgroundColor(Color.parseColor("#4DFF3737"));
                    default:
                        break;
                }
//                if (isPass == 0) return;
//                resetPwd(smsCode, password, password_confirm);
            }
        });
        iv_look_up.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(et_password.getText().toString().trim())) return;
                look_up = !look_up;
                if (look_up) {
                    iv_look_up.setImageResource(R.drawable.icon_look_down);
                    et_password.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    iv_look_up.setImageResource(R.drawable.icon_look_up);
                    et_password.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }
            }
        });
        iv_look_up_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(et_password_confirm.getText().toString().trim())) return;
                look_up_confirm = !look_up_confirm;
                if (look_up_confirm) {
                    iv_look_up_confirm.setImageResource(R.drawable.icon_look_down);
                    et_password_confirm.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    iv_look_up_confirm.setImageResource(R.drawable.icon_look_up);
                    et_password_confirm.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }
            }
        });
        et_password.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b){
                    PointMgr.INSTANCE.sendEvent("cl_login_click_tab_17");
                    Log.e("PointMgr.INSTANCE.sendEvent","cl_login_click_tab_17");
                }
            }
        });
        et_password.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}

            @Override
            public void afterTextChanged(Editable s) {

                password = s.toString();
                tv_runtime_error.setVisibility(View.GONE);
                reset_line1.setBackgroundColor(Color.parseColor("#33000000"));
                reset_line2.setBackgroundColor(Color.parseColor("#33000000"));

                if (TextUtils.isEmpty(password_confirm)) {
                    return;
                }

                if (!MyTextUtils.INSTANCE.verificationPwdLength(password)) {
                    isPass = "NO_ENOUGH_LENGTH";
                    tv_button.setBackgroundResource(R.drawable.bg_f4f4f4_corner_8);
                    return;
                }

                if (MyTextUtils.INSTANCE.hasChinese(password) || !MyTextUtils.INSTANCE.verificationPwd(password)) {
                    isPass = "ERROR_PASSWORD";
                    tv_button.setBackgroundResource(R.drawable.bg_f4f4f4_corner_8);
                    return;
                }

                if (!TextUtils.equals(password_confirm, password)) {
                    isPass = "NO_SAME";
//                    if ( firstCompare ) {
//                        firstCompare = false;
//                        tv_button.setBackgroundResource(R.drawable.bg_f4f4f4_corner_8);
//                    } else {
//                        tv_button.setBackgroundResource(R.drawable.bg_gradient_b4ffcc_76efff_corner_8);
//                    }
                    tv_button.setBackgroundResource(R.drawable.bg_gradient_b4ffcc_76efff_corner_8);
                } else {
                    isPass = "SUCCESS";
                    tv_runtime_error.setVisibility(View.GONE);
                    reset_line1.setBackgroundColor(Color.parseColor("#33000000"));
                    reset_line2.setBackgroundColor(Color.parseColor("#33000000"));
                    tv_button.setBackgroundResource(R.drawable.bg_gradient_b4ffcc_76efff_corner_8);
                }
            }
        });

        et_password_confirm.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b){
                    PointMgr.INSTANCE.sendEvent("cl_login_click_tab_18");
                    Log.e("PointMgr.INSTANCE.sendEvent","cl_login_click_tab_18");
                }
            }
        });

        et_password_confirm.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}

            @Override
            public void afterTextChanged(Editable s) {

                password_confirm = s.toString();
                tv_runtime_error.setVisibility(View.GONE);
                reset_line1.setBackgroundColor(Color.parseColor("#33000000"));
                reset_line2.setBackgroundColor(Color.parseColor("#33000000"));

                if (!MyTextUtils.INSTANCE.verificationPwdLength(password_confirm)) {
                    isPass = "NO_ENOUGH_LENGTH";
                    tv_button.setBackgroundResource(R.drawable.bg_f4f4f4_corner_8);
                    return;
                }

                if (MyTextUtils.INSTANCE.hasChinese(password_confirm) || !MyTextUtils.INSTANCE.verificationPwd(password_confirm)) {
                    isPass = "ERROR_PASSWORD";
                    tv_button.setBackgroundResource(R.drawable.bg_f4f4f4_corner_8);
                    return;
                }

                if (!TextUtils.equals(password_confirm, password)) {
                    isPass = "NO_SAME";
//                    if ( firstCompare ) {
//                        firstCompare = false;
//                        tv_button.setBackgroundResource(R.drawable.bg_f4f4f4_corner_8);
//                    } else {
//                        tv_button.setBackgroundResource(R.drawable.bg_gradient_b4ffcc_76efff_corner_8);
//                    }
                    tv_button.setBackgroundResource(R.drawable.bg_gradient_b4ffcc_76efff_corner_8);
                } else {
                    isPass = "SUCCESS";
                    tv_runtime_error.setVisibility(View.GONE);
                    reset_line1.setBackgroundColor(Color.parseColor("#33000000"));
                    reset_line2.setBackgroundColor(Color.parseColor("#33000000"));
                    tv_button.setBackgroundResource(R.drawable.bg_gradient_b4ffcc_76efff_corner_8);
                }

            }
        });

    }

    @Override
    public void initData() {
        urlBean = new Gson().fromJson(SharePreUtil.getStringData("_getWebLinkConfig"),getWebLinkConfigBean.class);
        Map<String, String> params = new HashMap<>();
        showLoading();
        MianModle.Companion.getInstant().securitygetApplicationConfig(params, new HttpCallback(){

            @Override
            public void onFaill(@NonNull String e) {
                hideLoading();
            }

            @Override
            public void onSuccess(@NonNull String data) {
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    if (MianModle.Companion.getInstant().isSuccess(jsonObject)){
                        appConfigBean = GsonUtils.INSTANCE.getGson().fromJson(data, AppConfigBean.class);

                    }
                } catch (Exception e){
                    e.printStackTrace();
                }
                hideLoading();
            }
        });
    }
    private void resetPwd(String code, String password, String password_confirm) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("custId", ZiLiPageUserDataBean.getInstance().getCustomerId());
        LogUtils.logE("--- resetPwd custId:"+ZiLiPageUserDataBean.getInstance().getCustomerId());
        LogUtils.logE("--- resetPwd mobile:"+mobile);
        if (mobile != null) {
            showLoading();
            loginModle.resetZiLiPagePassword("56", mobile, code, password, password_confirm, new HttpCallback(){
                @Override
                public void onFaill(@NonNull String e) {
                    LogUtils.logE(" -- fail :"+e);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            T.showShort(getActivity(), "reset password fail");
                        }
                    });
                    hideLoading();
                }

                @Override
                public void onSuccess(@NonNull String data) {

                    LogUtils.logE(" -- reset password Success data:"+data);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
//                                                T.showShort(getActivity(), "reset password Success");
                            Intent intent = new Intent(ResetPasswordActivity.this, LoginActivity.class);
                            intent.putExtra("mobile", mobile);
                            startActivity(intent);
                            finish();
                        }
                    });
                    hideLoading();
                    finish();
                }
            });
        }
    }

    private void showHelp() {
        closeIme();
        View view = View.inflate(this, R.layout.popowin_help_list, null);
        PopupWindow popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popupWindow.showAtLocation(rightText, Gravity.BOTTOM, 0, 0);
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.5f;
        getWindow().setAttributes(lp);
        TextView tv_tv1 = view.findViewById(R.id.tv_tv1);
        TextView tv_tv2 = view.findViewById(R.id.tv_tv2);
        TextView tv_tv3 = view.findViewById(R.id.tv_tv3);
        TextView tv_tv4 = view.findViewById(R.id.tv_tv4);
        TextView tv_tv5 = view.findViewById(R.id.tv_tv5);
        tv_tv1.setOnClickListener(v -> {
            popupWindow.dismiss();
            Intent intent = new Intent();
            intent.setClass(this, WebViewActivity.class);
            intent.putExtra("url", urlBean.getData().getFacebookUrl());
            startActivity(intent);
        });
        tv_tv2.setOnClickListener(v -> {
            popupWindow.dismiss();
//            Intent intent = new Intent();
//            intent.setClass(this, WebViewActivity.class);
//            intent.putExtra("url", "baidu.com");
//            startActivity(intent);

            String phoneNumber = appConfigBean.getData().getWhatApp();
            Intent intent = new Intent(Intent.ACTION_DIAL);
            intent.setData(Uri.parse("tel:"+phoneNumber));
            startActivity(intent);

        });
        tv_tv3.setOnClickListener(v -> {
            popupWindow.dismiss();

            String phoneNumber = appConfigBean.getData().getContactNumber();
            Intent intent = new Intent(Intent.ACTION_DIAL);
            intent.setData(Uri.parse("tel:"+phoneNumber));
            startActivity(intent);

        });
        tv_tv4.setOnClickListener(v -> {
            popupWindow.dismiss();

            try {
                IntentUtils.openMail(this, appConfigBean.getData().getContactEmail());
            } catch (Exception e) {
                e.printStackTrace();
                ToastUtils.showLong(this, "No hay aplicación de buzón");
            }

        });
        tv_tv5.setOnClickListener(v -> {
            Intent intent = new Intent();
            intent.setClass(this, WebViewActivity.class);
            intent.putExtra("url", urlBean.getData().getFeedbackUrl());
            startActivity(intent);
            popupWindow.dismiss();
        });
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1.0f);
            }
        });
    }

    private void backgroundAlpha(float f) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = f;
        getWindow().setAttributes(lp);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View currentFocus = getCurrentFocus();
            if (currentFocus instanceof EditText) {
                EditText editText = (EditText) currentFocus;
                if (!isInSide(editText, ev) && isSoftInPutDisplayed()) {
                    closeIme();
                }
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    private Boolean isInSide(View currentFocus, MotionEvent ev) {
        int[] location = {0,0};
        currentFocus.getLocationInWindow(location);
        int left = location[0];
        int top = location[1];
        int right = left + currentFocus.getWidth();
        int bottom = top + currentFocus.getHeight();
        return (ev.getX() >= left && ev.getX() <= right && ev.getY() > top && ev.getY() < bottom);

    }

    private Boolean isSoftInPutDisplayed() {
        WindowInsetsCompat insetsCompat = ViewCompat.getRootWindowInsets(getWindow().getDecorView());
        return insetsCompat != null && insetsCompat.isVisible(WindowInsetsCompat.Type.ime());
    }

    private void closeIme() {
        if (getActivity().getCurrentFocus() == null) {
            return;
        }

        ((InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }

    @Override
    public void onStop(){
        super.onStop();
        hideLoading();
    }
}
